/*-------------------------------------------------------------*/
/*                                                             */
/*   Program to initialize CAEN C808/V812 discriminators       */
/*   Februar 2004 Daniela Mund                                 */
/*   Juni 2008    Bastian Maerkisch                            */
/*   Nov 2008     Bastian Maerkisch                            */
/*                                                             */
/*-------------------------------------------------------------*/

#include <fcntl.h>
#include <iostream>
#include <getopt.h>
#include <unistd.h>
using namespace std;

#include "Disc_V812.h"
#include "Disc_C808.h"
#include "disc_lib.h"
#include "sis3100_vme_calls.h"


int main(int argc, char **argv)
{
  CaenDiscriminator * disc;
  bool is_vme = true;
  int opt;
  
  char * camac_device = "/dev/cc32_1";
  const int station = 1;
  Camac_CC32 * camac;

  char * vme_device = "/dev/sis1100_00remote";
  unsigned discr_addr = 0xee0000;
  int crate;

  while ((opt = getopt(argc, argv, "cvh")) != -1) {
    switch (opt) {
    case 'c':
      is_vme = false;
      break;
    case 'v':
      is_vme = true;
      break;
    case 'h':
    default:
      cout << "Usage: " << argv[0] << "[-c|-v]" << endl;
      cout << "Options:" << endl;
      cout << "     " << "-c selects Camac discriminator" << endl;
      cout << "     " << "-v selects VME discriminator (default)" << endl;
      exit(EXIT_FAILURE);
    };
  }

  if (!is_vme) {
    camac = new Camac_CC32(camac_device);
    disc = new Disc_C808(*camac, station);
  } else {
    // open sis1100/3100 pci-to-vme link
    if (!(crate = open(vme_device, O_RDWR, 0))) {
      cerr << "ERROR: could not open \"" << vme_device << "\"" << endl;
      cerr.flush();
      exit(1);
    }
    disc = new Disc_V812(crate, discr_addr);
    //TODO: actually verify that we have the correct module here
    cout << "accessing VME module at address 0x" << hex << discr_addr << dec << endl; 
    cout << "manufacturer:  0x" << hex << ((Disc_V812 *)disc)->GetManufacturerNumber() << dec << endl; 
    cout << "module type:   0x" << hex << ((Disc_V812 *)disc)->GetModuleType() << dec << endl;
    cout << "serial number: " << ((Disc_V812 *)disc)->GetSerialNumber() << endl;
    cout << "version:       " << ((Disc_V812 *)disc)->GetModuleVersion() << endl;
    cout << "fixed code:    0x" << hex << ((Disc_V812 *)disc)->GetFixedCode() << dec << endl;
  }

  disc_read_ini(*disc, "disc.ini");
  disc_show_settings(*disc);

  if (!is_vme)
    camac->Close();
  else
    close(crate);

  return 0;
}
